package com.pig4cloud.pig.common.biz.design;

import com.pig4cloud.pig.common.core.util.SpringContextHolder;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description : 过滤器链上下文容器
 * @author: lingnan
 * @date: 2023/6/19
 * @version: 1.0
 */
@Component
public final class AbstractChainContext<T> implements CommandLineRunner {

	private final Map<String, List<AbstractChainHandler>> handlerMap = new ConcurrentHashMap<>();


	public void handler(String mark, T param) {
		handlerMap.get(mark)
				.stream()
				.sorted(Comparator.comparingInt(Ordered::getOrder))
				.forEach(c -> c.handler(param));
	}


	/**
	 * Callback used to run the bean.
	 *
	 * @param args incoming main method arguments
	 */
	@Override
	public void run(String... args) {
		Map<String, AbstractChainHandler> beansOfType = SpringContextHolder.getApplicationContext().getBeansOfType(AbstractChainHandler.class);
		beansOfType.forEach((k, v) -> {
			List<AbstractChainHandler> handlers = handlerMap.getOrDefault(v.mark(), new ArrayList<>());
			handlers.add(v);
			handlerMap.put(v.mark(), handlers);
		});
	}
}
